<template>
    <div class="form-flow-setting">
        <el-dialog v-model="dialogVisible" title="表单流转设置" width="1600px" :close-on-click-modal="false"
            @close="handleClose">
            <div class="dialog-content">
                <div class="table-container">
                    <el-table :data="flowSettings" style="width: 100%" border row-key="NodeId" ref="flowTableRef">
                        <el-table-column type="index" label="序号" width="80" />
                        <el-table-column prop="NodeNo" label="节点编号" width="150" />
                        <el-table-column prop="NodeName" label="节点名称" />
                        <el-table-column label="操作人" width="200">
                            <template #default="{ row }">
                                <el-select v-model="row.OperatorUserId" placeholder="请选择操作人" style="width: 100%;"
                                    clearable>
                                    <el-option v-for="user in users" :key="user.AccountId" :label="user.NickName"
                                        :value="user.AccountId" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="PrevNodeName" label="上级节点名称" width="150">
                            <template #default="{ row, $index }">
                                {{ $index > 0 ? flowSettings[$index - 1].NodeName : '' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="NextNodeName" label="下级节点名称" width="150">
                            <template #default="{ row, $index }">
                                {{ $index < flowSettings.length - 1 ? flowSettings[$index + 1].NodeName : '' }}
                                    </template>
                        </el-table-column>
                        <el-table-column prop="FormName" label="表单名称" width="150" />
                        <el-table-column prop="TypeName" label="分类名称" width="150" />
                        <el-table-column fixed="right" label="操作列" min-width="120">
                            <template #default="{ row }">
                                <el-button link type="primary" size="small" @click="handleDelete(row)">删除</el-button>
                                <el-button link type="primary" size="small" @click="handleEdit(row)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="button-container">
                    <el-button type="primary" @click="handleAdd">添加节点</el-button>
                    <el-button type="success" @click="handleSave">保存设置</el-button>
                </div>
            </div>
        </el-dialog>

        <!-- 节点编辑对话框 -->
        <el-dialog v-model="editDialogVisible" :title="editingNode ? '编辑节点' : '添加节点'" width="1200px"
            :close-on-click-modal="false">
            <el-form ref="nodeFormRef" :model="nodeForm" :rules="nodeRules" label-width="100px">
                <el-form-item label="节点名称" prop="nodeName">
                    <el-input v-model="nodeForm.nodeName" placeholder="请输入节点名称" />
                </el-form-item>
                <el-form-item label="节点类型" prop="nodeType">
                    <el-select v-model="nodeForm.nodeType" placeholder="请选择节点类型" style="width: 100%">
                        <el-option label="开始节点" :value="1" />
                        <el-option label="审批节点" :value="2" />
                        <el-option label="结束节点" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item label="操作人" prop="operator">
                    <el-select v-model="nodeForm.operator" placeholder="请选择操作人" style="width: 100%">
                        <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上级节点" prop="parentNode">
                    <el-select v-model="nodeForm.parentNode" placeholder="请选择上级节点" style="width: 100%">
                        <el-option v-for="node in availableParentNodes(nodeForm)" :key="node.id" :label="node.nodeName"
                            :value="node.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="下级节点" prop="childNode">
                    <el-select v-model="nodeForm.childNode" placeholder="请选择下级节点" style="width: 100%">
                        <el-option v-for="node in availableChildNodes(nodeForm)" :key="node.id" :label="node.nodeName"
                            :value="node.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleNodeSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetFromNode, SaveFormNodeDetails } from '@/api/formNode'
import { GetAccount } from '@/api/user'

import { useRoute } from 'vue-router'
//import { v4 as uuidv4 } from 'uuid'
import draggable from 'vuedraggable'
import Sortable from 'sortablejs'

const route = useRoute()
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const flowSettings = ref([])
const users = ref([])
const editingNode = ref(null)
const nodeFormRef = ref(null)
const flowTableRef = ref(null)
const formId = ref('')

const nodeForm = ref({
    id: '',
    nodeName: '',
    nodeType: 2,
    operator: '',
    parentNode: '',
    childNode: '',
    nodeNumber: ''
})

const nodeRules = {
    nodeName: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
    nodeType: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
    operator: [{ required: true, message: '请选择操作人', trigger: 'change' }]
}

// 获取节点类型名称
const getNodeTypeName = (type) => {
    const types = {
        1: '开始节点',
        2: '审批节点',
        3: '结束节点'
    }
    return types[type] || '未知类型'
}

// 获取可选的上级节点
const availableParentNodes = (currentNode) => {
    return flowSettings.value.filter(node => {
        // 不能选择自己作为上级节点
        if (node.id === currentNode.id) return false
        // 不能选择自己的下级节点作为上级节点
        if (node.id === currentNode.childNode) return false
        // 不能选择结束节点作为上级节点
        if (node.nodeType === 3) return false
        return true
    })
}

// 获取可选的下级节点
const availableChildNodes = (currentNode) => {
    return flowSettings.value.filter(node => {
        // 不能选择自己作为下级节点
        if (node.id === currentNode.id) return false
        // 不能选择自己的上级节点作为下级节点
        if (node.id === currentNode.parentNode) return false
        // 不能选择开始节点作为下级节点
        if (node.nodeType === 1) return false
        return true
    })
}

// 拖动排序功能
watch(dialogVisible, (val) => {
    if (val) {
        nextTick(() => {
            setTimeout(() => {
                initSortable()
            }, 500)
        })
    }
})

const initSortable = () => {
    const table = flowTableRef.value
    if (!table) return
    const tbody = table.$el.querySelector('.el-table__body-wrapper tbody')
    if (!tbody) return
    if (tbody._sortable_inited) return
    tbody._sortable_inited = true
    Sortable.create(tbody, {
        animation: 150,
        handle: 'tr',
        onEnd: (evt) => {
            if (evt.oldIndex === evt.newIndex) return
            // 重新排序 flowSettings
            const oldIndex = evt.oldIndex
            const newIndex = evt.newIndex
            const moved = flowSettings.value.splice(oldIndex, 1)[0]
            flowSettings.value.splice(newIndex, 0, moved)
            // 更新上下级编号（PrevNodeName/NextNodeName存编号）
            flowSettings.value.forEach((row, idx, arr) => {
                row.PrevNodeName = idx > 0 ? arr[idx - 1].NodeNo : ''
                row.NextNodeName = idx < arr.length - 1 ? arr[idx + 1].NodeNo : ''
            })
        }
    })
}

// 处理操作人变更
const handleOperatorChange = (row) => {
    // 可以在这里添加额外的处理逻辑
}

// 处理上级节点变更
const handleParentNodeChange = (row) => {
    // 更新相关节点的关系
    const parentNode = flowSettings.value.find(node => node.id === row.parentNode)
    if (parentNode) {
        parentNode.childNode = row.id
    }
}

// 处理下级节点变更
const handleChildNodeChange = (row) => {
    // 更新相关节点的关系
    const childNode = flowSettings.value.find(node => node.id === row.childNode)
    if (childNode) {
        childNode.parentNode = row.id
    }
}

// 处理编辑
const handleEdit = (row) => {
    editingNode.value = row
    nodeForm.value = { ...row }
    editDialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该节点吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = flowSettings.value.findIndex(item => item.id === row.id)
        if (index > -1) {
            // 更新相关节点的关系
            const node = flowSettings.value[index]
            const parentNode = flowSettings.value.find(n => n.id === node.parentNode)
            const childNode = flowSettings.value.find(n => n.id === node.childNode)

            if (parentNode && childNode) {
                parentNode.childNode = childNode.id
                childNode.parentNode = parentNode.id
            } else if (parentNode) {
                parentNode.childNode = ''
            } else if (childNode) {
                childNode.parentNode = ''
            }

            flowSettings.value.splice(index, 1)
            ElMessage.success('删除成功')
        }
    }).catch(() => { })
}

// 处理添加
const handleAdd = () => {
    editingNode.value = null
    nodeForm.value = {
        id: uuidv4(),
        nodeName: '',
        nodeType: 2,
        operator: '',
        parentNode: '',
        childNode: '',
        nodeNumber: ''
    }
    editDialogVisible.value = true
}

// 处理节点提交
const handleNodeSubmit = async () => {
    if (!nodeFormRef.value) return

    await nodeFormRef.value.validate(async (valid) => {
        if (valid) {
            if (editingNode.value) {
                // 更新现有节点
                const index = flowSettings.value.findIndex(item => item.id === editingNode.value.id)
                if (index > -1) {
                    flowSettings.value[index] = { ...nodeForm.value }
                }
            } else {
                // 添加新节点
                flowSettings.value.push({ ...nodeForm.value })
            }
            editDialogVisible.value = false
            ElMessage.success(editingNode.value ? '更新成功' : '添加成功')
        }
    })
}

// 处理保存
const handleSave = async () => {
    try {
        // 验证节点关系
        const hasError = flowSettings.value.some(node => {
            if (node.nodeType === 1 && node.parentNode) {
                ElMessage.error('开始节点不能有上级节点')
                return true
            }
            if (node.nodeType === 3 && node.childNode) {
                ElMessage.error('结束节点不能有下级节点')
                return true
            }
            return false
        })

        if (hasError) return

        // 构建树形结构
        const buildTree = (nodes) => {
            const nodeMap = new Map(nodes.map(node => [node.id, { ...node, children: [] }]))
            const tree = []

            nodes.forEach(node => {
                const nodeWithChildren = nodeMap.get(node.id)
                if (node.parentNode) {
                    const parent = nodeMap.get(node.parentNode)
                    if (parent) {
                        parent.children.push(nodeWithChildren)
                    }
                } else {
                    tree.push(nodeWithChildren)
                }
            })

            return tree
        }

        const treeData = buildTree(flowSettings.value)

        // 验证节点连接
        const validateConnections = (node) => {
            if (node.children.length > 1) {
                ElMessage.error(`节点 "${node.nodeName}" 有多个下级节点`)
                return false
            }
            return node.children.every(validateConnections)
        }

        if (!validateConnections(treeData[0])) {
            return
        }

        // 更新节点编号
        const updateNodeNumbers = (node, parentNumber = '') => {
            const currentNumber = parentNumber ? `${parentNumber}.${node.nodeNumber}` : node.nodeNumber
            node.nodeNumber = currentNumber
            node.children.forEach(child => updateNodeNumbers(child, currentNumber))
        }

        updateNodeNumbers(treeData[0])

        // 保存设置
        // 1. 组装后端需要的Nodes参数
        const nodes = flowSettings.value.map(item => {
            // 查找操作人名称
            let userName = ''
            const user = users.value.find(u => u.AccountId === item.OperatorUserId)
            if (user) userName = user.NickName
            return {
                NodeId: item.NodeId || 0,
                NodeNo: item.NodeNo,
                NodeName: item.NodeName,
                UserId: item.OperatorUserId,
                UserName: userName,
                PrevNodeNo: item.PrevNodeName || '',
                NextNodeNo: item.NextNodeName || ''
            }
        })
        await SaveFormNodeDetails({
            FormId: formId.value,
            Nodes: nodes
        })
        console.log('Saving nodes payload:', { FormId: formId.value, Nodes: nodes })
        ElMessage.success('保存成功')
        dialogVisible.value = false
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
    }
}

// 处理关闭
const handleClose = () => {
    flowSettings.value = []
    editingNode.value = null
    nodeForm.value = {
        id: '',
        nodeName: '',
        nodeType: 2,
        operator: '',
        parentNode: '',
        childNode: '',
        nodeNumber: ''
    }
}

// 打开对话框
const open = async (id) => {
    formId.value = id
    try {
        const [flowData, userData] = await Promise.all([
            GetFromNode({ FormId: id, PageIndex: 1, PageSize: 100 }),
            GetAccount()
        ])
        console.log('GetFromNode返回:', flowData)
        if (flowData.data && flowData.data.Result && flowData.data.Result.Data) {
            flowSettings.value = flowData.data.Result.Data
            // 根据节点顺序更新上下级编号 (PrevNodeName/NextNodeName存编号)
            flowSettings.value.forEach((row, idx, arr) => {
                row.PrevNodeName = idx > 0 ? arr[idx - 1].NodeNo : ''
                row.NextNodeName = idx < arr.length - 1 ? arr[idx + 1].NodeNo : ''
            })

            // 反填操作人
            flowSettings.value.forEach(item => {
                if (item.OperatorUserId) {
                    // 保证下拉框选中
                    item.OperatorUserId = item.OperatorUserId
                } else if (item.UserId) {
                    // 兼容后端返回UserId字段
                    item.OperatorUserId = item.UserId
                }
            })
        } else {
            flowSettings.value = []
        }
        users.value = userData.data?.data || []
        dialogVisible.value = true
    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error('获取数据失败')
    }
}

// 暴露方法给父组件
defineExpose({
    open
})
</script>

<style scoped>
.form-flow-setting {
    width: 100%;
}

.dialog-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.table-container {
    max-height: 500px;
    overflow-y: auto;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-table__row) {
    cursor: move;
}

:deep(.el-table__row.sortable-ghost) {
    opacity: 0.5;
    background: #f0f0f0;
}

:deep(.el-table__row.sortable-drag) {
    background: #f5f7fa;
}
</style>